/*
	运算符重载
   1.实验题目
   设计一个字符串类String
 	2.实验目的
   熟悉运算符重载
   3.要求：
    1、使用”=“完成两个运算符的赋值
    2、使用”==“判断两个字符串是否相等
    3、使用”+=”完成两个字符串的连接
    4、使用”>”实现两个字符串的比较
*/

#include <iostream>
#include <cstring>

using namespace std;

class String {
	private:
		char * string;
	
	public:
		String(const char * s = "") {
			string = new char[strlen(s)];
			strcpy(string, s);
		}
		~String() {
			cout << "Deconstring..." << endl;
			delete [] string;
		}
		String(const String & obj) {
			// 如果初始化赋值，则不进入主构造器，直接进入拷贝构造器
			//		例如: String obj1 = obj2; // obj2已定义

			string = new char[strlen(obj.string)];
			strcpy(string, obj.string);
			// *this = obj; // 重载赋值运算符 @TODO
		}

		String & operator = (const String & obj);
		bool operator == (const String & obj);
		String & operator += (const String & obj);
		String operator + (const String & obj);
		bool operator > (const String & obj);

		friend istream & operator >> (istream & stream, String & obj);
		friend ostream & operator << (ostream & stream, const String & obj);
};

String & String::operator = (const String & obj) {
	delete [] string;
	string = new char[strlen(obj.string)];
	strcpy(string, obj.string);

	return * this;
}

bool String::operator == (const String & obj) {
	if(!strcmp(string, obj.string))
		return true;
	return false;
}

String & String::operator += (const String & obj) {
	char * temp = new char[strlen(string)];
	strcpy(temp, string);
	
	// @TODO
	// delete [] string;
	string = new char[strlen(string) + strlen(obj.string)];
	strcpy(string, temp);
	strcat(string, obj.string);
	
	delete [] temp;

	return * this;
}

String String::operator + (const String & obj) {
	String temp;
	delete [] temp.string;

	temp.string = new char[strlen(string)+strlen(obj.string)];
	strcpy(temp.string, string);
	strcat(temp.string, obj.string);

	return temp;
}

bool String::operator > (const String & obj) {
	if(strcmp(string, obj.string) == 1)
		return true;
	return false;
}

istream & operator >> (istream & stream, String & obj) {
	stream >> obj.string;
	
	return stream;
}

ostream & operator << (ostream & stream, const String & obj) {
	stream << obj.string;

	return stream;
}

int main(int argc, char * argv[]) {
	String s1("I'm Potter.");
	cout << "s1: " << s1 << endl;

	String s2 = s1;
	cout << "s2(s1): " << s2 << endl;
	
	String s3;
	s3 = s1;
	cout << "s3 = s1: " << s1 << endl;

	String s4("\n\t If I love you, I will love you forever.");
	String s5;
	s5 = s1 + s4;
	cout << "s5=s1+s4: " << s5 << endl;

	String s6("\n\t I miss you.");
	s5 += s6;
	cout << "S5 += s6: " << s5 << endl;

	if(s1 == s2)
		cout << "s1 == s2" << endl;
	
	if(!(s1 == s5))
		cout << "s1 != s5" << endl;
		
	return 0;
}
